/**
 * Created by wtfssd on 2017/9/15.
 */

import React, {Component} from 'react'
import {
    StyleSheet, Text, View, ScrollView, Image, TouchableOpacity, FlatList, ImageBackground, RefreshControl
} from 'react-native'
import PropTypes from 'prop-types';
import {connect} from 'react-redux'
import {Flex, Button, Badge, List, WhiteSpace, Popup} from 'antd-mobile'
import CommonStyle, {Color, size, SCREEN} from '../../assets/styles/index'
import NavigationBar from 'react-native-navbar'
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome'
import {Actions} from 'react-native-router-flux'
import {Star, Line, Counter, BackButton, MyIcon, ShareButton, LoadingView} from '../common/index'
import {productInCart, countInCart} from '../../utils/tools'

const ListItem = List.Item;

class Page extends Component {
    constructor(props) {
        super(props);
        this.state = {
            refresh: false,
            currentTab: 0,
            productCount: 0,
        };
    }

    /*组件将要加载*/
    componentWillMount() {
        let payload = {
            store_id: this.props.store_id,
            id: this.props.id,
            product_id: this.props.id,
        };
        if (this.props.auth.isSignIn) {
            payload['user_id'] = this.props.auth.profile.member_id;
        }
        this.props.dispatch({
            type: 'product/fetchDetail',
            payload
        })
    }


    /*显示内容切换*/
    onTabChange(currentTab) {this.setState({currentTab});}

    //添加到购物车
    addShopCart() {
        const {product: {loading, detail}, dispatch, auth} = this.props;

        if (!auth.isSignIn) {
            Actions.auth({from: 'productDetail'});
            return;
        }
        dispatch({
            type: 'cart/add',
            payload: {user_id: auth.profile.member_id, product_id: detail.id, count: 1, store_id: detail.store_id}
        })
    }

    /**
     * 购物车增加
     */
    onPlusCartProduct = () => {
        const {dispatch, product: {detail}, auth} = this.props;

        dispatch({
            type: 'cart/add',
            payload: {...detail, count: 1, product_id: detail.id}
        })
    };

    /**
     * 购物车减少
     */
    onMinusCartProduct = () => {
        const {dispatch, product: {detail}, auth} = this.props;

        dispatch({
            type: 'cart/add',
            payload: {...detail, count: -1, product_id: detail.id}
        })
    };

    /**
     * 收藏
     */
    addFav = () => {
        const {product: {loading, detail}, dispatch} = this.props;
        let payload = {
            store_id: this.props.store_id,
            product_id: this.props.id
        };
        if (this.props.auth.isSignIn) {
            payload['id'] = this.props.auth.profile.member_id;
        } else {
            Actions.auth({from: 'productDetail'});
            return;
        }

        dispatch({
            type: 'product/addFav',
            payload
        })
    };

    /*显示商品头*/
    renderHeader = () => {
        let is_collect = this.props.product.detail.is_collect;
        return (
            <ImageBackground source={{uri: this.props.product.detail.preview}}
                             style={Styles.header}>
                <TouchableOpacity style={is_collect === 1 ? Styles.btn1Active : Styles.btn1} onPress={this.addFav}>
                    <FontAwesomeIcon name="heart-o" size={size(15)} color={is_collect === 1 ? 'red' : '#ccc'}/>
                    <Text style={{color:is_collect === 1 ? 'red' : '#ccc',fontSize:16}}>{is_collect === 1 ? '已收藏' : '收藏商品'}</Text>
                </TouchableOpacity>
            </ImageBackground>
        )
    };

    goToShopCart = () => {
        // Actions.popTo('tabView');
        Actions.jump('shopCart');
    };

    /*显示详情*/
    renderDetail() {
        const {product: {detail}} = this.props;
        return (
            <View style={{backgroundColor: 'white'}}>
                <Flex align="start" style={{padding: 10}}>
                    <Text style={[CommonStyle.text1, {marginRight: 10}]}>商品简介</Text>
                    <View style={{width: size(290)}}>
                        <Text>{detail.summary}</Text>
                    </View>
                </Flex>
            </View>
        )
    }


    //评价item
    renderCommentItem({item}) {
        return (
            <Flex style={{backgroundColor: 'white', padding: 10}} align="start">
                {/*<Image source={{uri: icon}}*/}
                {/*style={{width: size(35), height: size(35), borderRadius: size(17.5)}}/>*/}
                <Flex direction="column" style={{flex: 1, paddingLeft: 10}} align="start">
                    <Text style={[CommonStyle.text1, CommonStyle.pdb5]}>{item.get_comment.get_user.username}</Text>
                    <Text style={[CommonStyle.text4, CommonStyle.pdb5]}>{item.created_at}</Text>
                    <Text
                        style={[CommonStyle.text1, CommonStyle.pdb5, {lineHeight: 16}]}>{item.get_comment.evaluate}</Text>
                    <Star stars={item.get_comment.star}/>
                </Flex>
            </Flex>
        )
    }

    /*显示评论*/
    renderCommon() {


        const {comments} = this.props.product;
        if (!comments || (Array.isArray(comments) && comments.length <= 0) || typeof comments === 'undefined') {
            return (
                <View style={Styles.noCommont}>
                    <Text>暂无评论</Text>
                </View>
            )
        }
        return (
            <FlatList data={comments}
                      extraData={this.state}
                      style={{flex: 1}}
                      ItemSeparatorComponent={Line.bind(null, {height: 1, backgroundColor: '#F2F2F2'})}
                      renderItem={this.renderCommentItem.bind(this)}
                      keyExtractor={(item, index) => item.id}
            />
        )
    }

    /*当前显示内容*/
    renderCurrentTapPage() {
        if (this.state.currentTab === 0) {
            return this.renderDetail();
        } else {
            return this.renderCommon();
        }
    }

    /*下拉刷新*/
    onRefresh = () => {
        this.setState({refresh: true});
        setTimeout(() => {
            this.setState({refresh: false});
        }, 2000)
    };

//     {/*rightButton={<ShareButton/>}*/}
    render() {
        const {product: {loading, detail}} = this.props;
        return (
            <View style={CommonStyle.container}>
                <NavigationBar tintColor={Color.primary}
                               statusBar={{style: 'light-content'}}
                               leftButton={<BackButton/>}


                               title={{title: this.props.title, tintColor: 'white'}}
                />
                <LoadingView loading={loading}>
                    <View style={Styles.container}>
                        <ScrollView>
                            <List renderHeader={this.renderHeader}>
                                <ListItem arrow="horizontal" extra="进入店铺"
                                          onClick={Actions.shopDetail.bind(null, {store_id: detail.store_id})}>
                                    <Text>{detail.store_name}</Text>
                                </ListItem>

                                <ListItem>
                                    <Text>商品名称：<Text>{detail.name}</Text></Text>
                                </ListItem>

                                <ListItem>
                                    <Flex align="center">
                                        <Text>规 格：</Text>
                                        <View style={Styles.btn2}>
                                            <Text style={[{color: Color.primary}]}>
                                                {detail.spec}
                                            </Text>
                                        </View>
                                    </Flex>
                                </ListItem>
                                <ListItem arrow="horizontal">
                                    <Text>价格：{Number(detail.price).toFixed(2)}</Text>
                                </ListItem>
                                <ListItem arrow="horizontal">
                                    <Text>联系商家</Text>
                                </ListItem>
                            </List>
                            <WhiteSpace/>
                            <Flex style={{borderBottomWidth: 1, borderBottomColor: '#ccc'}}>
                                <TouchableOpacity
                                    style={[Styles.btn3, {borderBottomColor: this.state.currentTab === 0 ? Color.primary : 'white'}]}
                                    onPress={this.onTabChange.bind(this, 0)} activeOpacity={0.9}>
                                    <Text
                                        style={{color: this.state.currentTab === 0 ? Color.primary : 'black'}}>商品详情</Text>
                                </TouchableOpacity>
                                <TouchableOpacity
                                    style={[Styles.btn3, {borderBottomColor: this.state.currentTab === 1 ? Color.primary : 'white'}]}
                                    onPress={this.onTabChange.bind(this, 1)} activeOpacity={0.9}>
                                    <Text
                                        style={{color: this.state.currentTab === 1 ? Color.primary : 'black'}}>评价</Text>
                                </TouchableOpacity>
                            </Flex>

                            {this.renderCurrentTapPage()}
                        </ScrollView>
                    </View>
                    <View style={Styles.bottomBar}>
                        <TouchableOpacity onPress={this.goToShopCart}>
                            <Badge text={this.props.auth.isSignIn ? countInCart(this.props.cart.list) : 0}>
                                <MyIcon name="gouwuche" size={size(28)} color={Color.primary}/>
                            </Badge>
                        </TouchableOpacity>
                        <Counter
                            count={this.props.auth.isSignIn ? productInCart(this.props.cart.list, this.props.product.detail.id) : 0}
                            onMinus={this.onMinusCartProduct} onPlus={this.onPlusCartProduct}/>
                        <Button onClick={this.addShopCart.bind(this)}
                                disabled={Number(detail.is_shelves) === 0}
                                title='加入购物车' type="primary"
                                style={[Styles.btn, Number(detail.is_shelves) === 0 ? Styles.disable : null]}>{Number(detail.is_shelves )=== 0 ? '已下架' : '加入购物车'}</Button>
                    </View>
                </LoadingView>

            </View>
        )
    }
}

const Styles = StyleSheet.create({
    container: {
        display: 'flex',
        flex: 1,
    },
    bottomBar: {
        display: 'flex',
        flexDirection: 'row',
        height: size(52),
        backgroundColor: 'white',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingLeft: 10
    },
    btn: {
        width: size(150),
        height: '100%',
        borderRadius: 0
    },

    disable: {
        backgroundColor: '#AAAAAA'
    },

    header: {
        height: size(375),
        width: size(375),
        display: 'flex',
        justifyContent: 'flex-end',
        alignItems: 'flex-end',
        padding: 10,
    },
    btn1: {
        backgroundColor: 'transparent',
        display: 'flex',
        flexDirection: 'row',
        borderColor: '#ccc',
        borderWidth: 1,
        borderRadius: size(15),
        paddingHorizontal: 10,
        alignItems: 'center',
        paddingVertical: 2
    },

    btn1Active: {
        backgroundColor: 'transparent',
        display: 'flex',
        flexDirection: 'row',
        borderColor: 'red',
        borderWidth: 1,
        borderRadius: size(15),
        paddingHorizontal: 10,
        alignItems: 'center',
        paddingVertical: 2
    },
    btn2: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        padding: 2,
        borderColor: Color.primary,
        borderWidth: 1,
        borderRadius: 4
    },
    btn3: {
        display: 'flex',
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'white',
        height: size(40),
        borderBottomWidth: size(2),
        borderBottomColor: 'white'
    },

    noCommont: {
        width: SCREEN.width,
        height: 100,
        backgroundColor: '#fff',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
    }

});

export default connect(
    ({auth, product, cart}) => ({auth, product, cart})
)(Page)



